package restapi_1.service;

import org.springframework.stereotype.Service;
import restapi_1.commodity.Commodity;

import java.util.*;

//@Service注解用于类上,标记当前类是一个service类,
// 加上该注解会将当前类自动注入到spring容器中,不需要再在applicationContext.xml文件定义bean了
@Service
public class CommodityService {
    private Map<Long, Commodity> commodityMap= Collections.synchronizedMap(new HashMap<Long,Commodity>());

    public  Commodity addCom(Commodity c){
        commodityMap.put(c.getId(),c);
        return c;
    }
    public List<Commodity> findAll() {
        List<Commodity> result=new ArrayList<>();
        for (Commodity c: commodityMap.values()){
            result.add(c);
        }
        return result;
    }

    public Commodity getCom(Long id){
        return commodityMap.get(id);
    }
    public void upDateCom(Long id,Commodity commodity){
        Commodity c2=commodityMap.get(id);
        c2.setName(commodity.getName());
        c2.setPrice(commodity.getPrice());
        c2.setIfSold(commodity.isIfSold());
        commodityMap.put(id,c2);
    }

    public void deleteCom(Long id){
        commodityMap.remove(id);
    }

    public List<Commodity> selectCom(String name, Boolean sold) {
        List<Commodity> result=new ArrayList<>();
        for (Commodity c: commodityMap.values()){
            if (name!=null && !c.getName().contains(name)) {
                continue;
            }
            if (sold!=null && !sold.equals(c.isIfSold())) {
                continue;
            }
            result.add(c);
        }
        return result;
    }
}
